/*
 * The MIT License
 *
 * Copyright 2014 David Rodenas Pico.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package edu.uoc.sd.fr14.comp;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import edu.uoc.sd.fr14.mesg.Message;

/**
 * Component that reads messages from a socket component.
 * 
 * Output:
 * - output: messages read from the socket
 * 
 * @author drodenas
 */
public class SocketListenerComponent extends Component {

    private static final edu.uoc.sd.fr14.model.Logger log = edu.uoc.sd.fr14.model.Logger.get("ListenerComponent");
    
    private final int port; // for logger
    private volatile ServerSocket serverSocket;
    private volatile boolean stopped;    
    
    private final Set<Receiver> receivers = Collections.newSetFromMap(new ConcurrentHashMap<Receiver, Boolean>());
    
    public SocketListenerComponent(final int port) {
        super("listener-"+port);
        this.port = port;
        
        // try to create the port and fail if it is not possible
        try {
            serverSocket = new ServerSocket(port);
            log.debug(port, "listen start");
        } catch (IOException ex) {
            // first time should be bindeable
            throw new RuntimeException(ex);
        }
        
        // start processes
        createProcessor("accept", new Runnable() {
            @Override
            public void run() {
                accept(port);
            }
        });
    }

    @Override
    protected void process(Message message) {
    }

    @Override
    public void stop() {
        super.stop();
        
        // do not loop for accepts more
        stopped = true;
        
        // socket is no more needed
        try {
            ServerSocket current = serverSocket;
            if (current != null) {
                current.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(SocketListenerComponent.class.getName()).log(Level.SEVERE, null, ex);
        }
        serverSocket = null;
        
        // stop all active receivers
        for (Receiver receiver : receivers) {
            receiver.stop();
        }
    }
    
    private int receiverNumber = 0;
    private void accept(int port) {

        if (serverSocket == null && !stopped) {
            try { serverSocket = new ServerSocket(port); } catch (IOException ex) {}            
            log.debug(port, "listen retryied");
        }
        
        try {
            // accept a new connection
            Socket socket = serverSocket.accept();
            log.debug(port, "accepted connection from '"+socket.getRemoteSocketAddress()+"'");
            
            // create the receiver, register, and execute in a sepparated thread
            String receiverName = "receiver" + (++receiverNumber);
            Receiver receiver = new Receiver(socket, receiverName);
            receivers.add(receiver);
            createProcessor(receiverName, receiver);

        } catch (IOException ex) {
            log.debug(port, "socket exception closing port");
            
            // if exception try to close the connection
            try { serverSocket.close(); } catch (IOException | NullPointerException ex1) {}
            if (!stopped) {
                // a small sleep to not consume too many resources
                try { Thread.sleep(3000); } catch (InterruptedException ex1) {}
                serverSocket = null;
            }
        }
        
    }
    
    private class Receiver implements Runnable {
        private final String id;
        private final Socket socket;
        private ObjectInputStream input;
        private final String receiverName;

        public Receiver(Socket socket, String receiverName) throws IOException {
            this.id = port+"|"+socket.getRemoteSocketAddress();
            this.socket = socket;
            this.receiverName = receiverName;
            // object stream for receiving messages
            this.input = new ObjectInputStream(socket.getInputStream());
        }

        public void stop() {
            // stop receiving messages
            receivers.remove(this);
            stopProcessor(receiverName);
            // the socket is no more required
            try { socket.close(); } catch (IOException ex) {}
        }
        
        @Override
        public void run() {
            try {
                // while receiver is active
                // receive a message
                Message message = (Message) input.readObject();
                log.debug(id, "received message '"+message+"'");
                
                // send through the queue
                deliver(message);
            } catch (ClassNotFoundException ex) {
                // report protoco errors
                Logger.getLogger(SocketListenerComponent.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                log.debug(id, "connection failure, closing '"+ex.getMessage()+"'");
                stop();
                //Logger.getLogger(MessageListener.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
    }
    
}
